package org.dawnmew.jpurewave;

/**
 * Implements a pure Java sound system, capable of OGG (music, dialog) and raw
 * PCM (sound effects) playback.
 *
 * @author dawnmew
 * @since 1.0
 *
 * Licensed under the MIT License.
 *
 * Copyright (c) 2012 dawnmew
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
import java.util.HashMap;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.*;

public class SoundSystem
{

    private static SoundSystem instance = null;
    public SourceDataLine outputLine = null;
    public SourceDataLine dialogLine = null;
    public static final FloatControl.Type volumeControlType = FloatControl.Type.VOLUME;
    public static final FloatControl.Type gainControlType = FloatControl.Type.MASTER_GAIN;
    private int controlMode = 0;
    private float minVolume = -35f; //MUST ALWAYS BE A NEGATIVE NUMBER, measured in dB
    private float maxVolumeTypeB = 0f; //Set later, only used in volumeControlType
    public final Object readyLock = new Object();
    private boolean ready = false;
    private float volMusic = 1.0f;
    private float volMusicNew = volMusic;
    private boolean volMusicChanged = false;
    private float volSound = 1.0f;
    private float volDialog = 1.0f;
    private boolean volMusicInit = false;
    private boolean volDialogInit = false;
    private boolean paused = false;
    public final Object musicDualCoreSync = new Object();
    public final Object musicPauseSync = new Object();
    public final Object musicLineSync = new Object();
    public final Object musicVolSync = new Object();
    public final Object dialogLineSync = new Object();
    private HashMap<String, MusicCore> musicCores = new HashMap<String, MusicCore>();
    private HashMap<String, String> soundEffects = new HashMap<String, String>();
    private String nowPlaying = "";
    private DialogInstance dialogInstance = null;
    private boolean musicStopped = true;
    private AudioFormat audioFormat = new AudioFormat(44100f, 16, 2, true, false);
    private boolean initialized = false;
    private boolean cutLines = false;
    private Thread volumeThread = null;

    public static SoundSystem getInstance()
    {
        if (instance == null)
        {
            instance = new SoundSystem();
        }
        return instance;
    }

    public void init()
    {
        if (initialized)
        {
            return;
        }
        if (cutLines)
        {
            return;
        }
        initialized = true;
        DataLine.Info datalineInfo = new DataLine.Info(SourceDataLine.class,
                audioFormat, AudioSystem.NOT_SPECIFIED);
        if (!AudioSystem.isLineSupported(datalineInfo))
        {
            System.err.println("Audio output line is not supported.");
            return;
        }
        synchronized (musicLineSync)
        {
            try
            {
                if (outputLine == null)
                {
                    outputLine = (SourceDataLine) AudioSystem.getLine(datalineInfo);
                    outputLine.open(audioFormat);
                    outputLine.start();
                }
            } catch (LineUnavailableException exception)
            {
                System.out.println("The audio output line could not be opened due "
                        + "to resource restrictions.");
                System.err.println(exception);
                return;
            } catch (IllegalStateException exception)
            {
                System.out.println("The audio output line is already open.");
                System.err.println(exception);
                return;
            } catch (SecurityException exception)
            {
                System.out.println("The audio output line could not be opened due "
                        + "to security restrictions.");
                System.err.println(exception);
                return;
            }
            if (outputLine.isControlSupported(gainControlType))
            {
                controlMode = 1;
                float minSoundLimit = ((FloatControl) outputLine.getControl(gainControlType)).getMinimum();
                if (minSoundLimit > minVolume)
                {
                    minVolume = minSoundLimit;
                }
            } else if (outputLine.isControlSupported(volumeControlType))
            {
                float minCheck = ((FloatControl) outputLine.getControl(volumeControlType)).getMinimum();
                if (minCheck > 0.1f || minCheck < -0.1f)
                {
                    System.out.println("Can't initialize volume-type audio system with nonzero minimum (" + Float.toString(minCheck) + ").");
                }
                controlMode = 2;
                maxVolumeTypeB = ((FloatControl) outputLine.getControl(volumeControlType)).getMaximum();
            }
        }
        synchronized (dialogLineSync)
        {
            try
            {
                if (dialogLine == null)
                {
                    dialogLine = (SourceDataLine) AudioSystem.getLine(datalineInfo);
                    dialogLine.open(audioFormat);
                    dialogLine.start();
                }
            } catch (LineUnavailableException exception)
            {
                System.out.println("The audio output line could not be opened due "
                        + "to resource restrictions.");
                System.err.println(exception);
            } catch (IllegalStateException exception)
            {
                System.out.println("The audio output line is already open.");
                System.err.println(exception);
            } catch (SecurityException exception)
            {
                System.out.println("The audio output line could not be opened due "
                        + "to security restrictions.");
                System.err.println(exception);
            }
        }
        volumeThread = new VolumeThread();
        volumeThread.setPriority(4);
        volumeThread.start();
    }

    public void waitUntilReadyMusic()
    {
        synchronized (readyLock)
        {
            while (!ready)
            {
                try
                {
                    readyLock.wait();
                } catch (InterruptedException ex)
                {
                    Logger.getLogger(MusicCore.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    public void setVolumeMusic(float vol)
    {
        synchronized (musicVolSync)
        {
            volMusicNew = vol;
            volMusicChanged = true;
            musicVolSync.notifyAll();
        }
    }

    private void setVolumeMusicInternal(float vol)
    {
        if (volMusicInit && volMusic == vol)
        {
            // Don't do anything if we're already at this volume.
            return;
        } else if (vol <= 0f)
        {
            vol = 0f;
        } else if (vol >= 1f)
        {
            vol = 1f;
        }
        volMusic = vol;
        synchronized (musicLineSync)
        {
            if (controlMode == 2)
            {
                ((FloatControl) outputLine.getControl(volumeControlType)).setValue(vol * maxVolumeTypeB);
            } else if (controlMode == 1)
            {
                vol = minVolume - (minVolume * vol);
                ((FloatControl) outputLine.getControl(gainControlType)).setValue(vol);
            }
        }
        if (!volMusicInit)
        {
            volMusicInit = true;
        }
    }

    public final void setVolumeSound(float vol)
    {
        if (vol <= 0f)
        {
            vol = 0f;
        }
        if (vol >= 1f)
        {
            vol = 1f;
        }
        volSound = vol;
    }

    public final void setVolumeDialog(float vol)
    {
        if (vol <= 0f)
        {
            vol = 0f;
        }
        if (vol >= 1f)
        {
            vol = 1f;
        }
        volDialog = vol;
        synchronized (dialogLineSync)
        {
            if (controlMode == 2)
            {
                ((FloatControl) dialogLine.getControl(volumeControlType)).setValue(vol * maxVolumeTypeB);
            } else if (controlMode == 1)
            {
                vol = minVolume - (minVolume * vol);
                ((FloatControl) dialogLine.getControl(gainControlType)).setValue(vol);
            }
        }
        if (!volDialogInit)
        {
            volDialogInit = true;
        }
    }

    public float getVolumeMusic()
    {
        return volMusic;
    }

    public float getVolumeSound()
    {
        return volSound;
    }

    public float getVolumeDialog()
    {
        return volDialog;
    }

    public void pauseMusic()
    {
        if (musicStopped)
        {
            return;
        }
        synchronized (musicPauseSync)
        {
            if (paused)
            {
                return;
            }
            paused = true;
            musicPauseSync.notifyAll();
            musicCores.get(nowPlaying).pause();
            outputLine.stop();
        }
    }

    public boolean isPausedMusic()
    {
        return paused;
    }

    public boolean isStoppedMusic()
    {
        return musicStopped;
    }

    public String getPlayingMusic()
    {
        return nowPlaying;
    }

    public void loadMusic(String musicRef, String musicPath, boolean wait)
    {
        musicCores.put(musicRef, new MusicCore(musicPath, this));
        MusicCore get = musicCores.get(musicRef);
        if (cutLines)
        {
            return;
        }
        if (get == null)
        {
            return;
        }
        get.start();
        if (wait)
        {
            get.waitUntilReady();
        }
    }

    public void playMusic()
    {
        if (!volMusicInit)
        {
            setVolumeMusic(1f);
        }
        if (cutLines)
        {
            return;
        }
        synchronized (musicPauseSync)
        {
            if (nowPlaying.equals("") || (!musicStopped && !paused))
            {
                return;
            }
            musicStopped = false;
            if (paused)
            {
                outputLine.start();
                paused = false;
                musicPauseSync.notifyAll();
            }
        }
        musicCores.get(nowPlaying).play();
    }

    public void playMusic(String musicRef)
    {
        if (cutLines)
        {
            return;
        }
        MusicCore get = musicCores.get(musicRef);
        if (get == null)
        {
            return;
        }
        stopMusic();
        nowPlaying = musicRef;
        playMusic();
    }

    public void stopMusic()
    {
        if (cutLines)
        {
            return;
        }
        if (nowPlaying.equals("") || musicStopped)
        {
            return;
        }
        musicCores.get(nowPlaying).reset();
        outputLine.flush();
        musicStopped = true;
    }

    public void loadSound(String soundRef, String soundPath)
    {
        soundEffects.put(soundRef, soundPath);
    }

    public void playSound(String soundRef)
    {
        if (cutLines)
        {
            return;
        }
        String soundPath = soundEffects.get(soundRef);
        if (soundPath == null)
        {
            return;
        }
        new SoundRawInstance(soundPath, volSound * (controlMode == 2 ? maxVolumeTypeB : 1f), controlMode, minVolume, this).start();
    }

    public void playDialog(String dialogPath)
    {
        if (cutLines)
        {
            return;
        }
        if (!volDialogInit)
        {
            setVolumeDialog(1f);
        }
        stopDialog();
        dialogInstance = new DialogInstance(dialogPath, this);
        dialogInstance.start();
    }

    public void stopDialog()
    {
        if (cutLines)
        {
            return;
        }
        if (dialogInstance != null)
        {
            dialogInstance.end();
            dialogInstance.waitUntilDone();
            synchronized (dialogLineSync)
            {
                dialogLine.flush();
            }
        }
        dialogInstance = null;
    }

    public void setAudioFormat(AudioFormat audioFormat)
    {
        this.audioFormat = audioFormat;
    }

    public Set<String> getAllSoundIDs()
    {
        return soundEffects.keySet();
    }

    public Set<String> getAllMusicIDs()
    {
        return musicCores.keySet();
    }

    public String getSoundFilepath(String id)
    {
        return soundEffects.get(id);
    }

    public String getMusicFilepath(String id)
    {
        return musicCores.get(id).getSource();
    }

    public void cutAudioLines()
    {
        cutLines = true;
    }

    private class VolumeThread extends Thread
    {

        @Override
        public void run()
        {
            while (true)
            {
                float newVol;
                synchronized (musicVolSync)
                {
                    while (true)
                    {
                        if (volMusicChanged)
                        {
                            volMusicChanged = false;
                            newVol = volMusicNew;
                            break;
                        }
                        try
                        {
                            musicVolSync.wait(10);
                        } catch (InterruptedException ex)
                        {
                            Logger.getLogger(SoundSystem.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
                setVolumeMusicInternal(newVol);
            }
        }
    }
}
